<template>
  <view>
    <hx-navbar ref="hxnb" :config="config" @clickBtn="clickBtn">
      <view slot="bottom">
        <template>
          <view class="input-product">
            <u-search
              placeholder="搜索或添加产品"
              v-model="searchData.keywords"
              @change="onSearchChange"
              :showAction="false"
            ></u-search>
          </view>
          <view
            v-if="
              page_source === 'cgd' ||
              page_source === 'xsd' ||
              page_source === 'thjs' ||
              page_source === 'khdd' ||
              'cgdreturn'
            "
            class="search-title"
          >
            <view v-if="warehouse != {}">
              <text class="label">{{ warehouse.name }}</text>
            </view>
            <view class="warehouse" @click="changeWarehouse">
              <text>换仓库</text>
            </view>
          </view>
        </template>
      </view>
    </hx-navbar>
    <u-grid ref="tabBarSearch" :border="false" :class="['tabBarSearch', type]">
      <u-grid-item
        v-for="(baseListItem, baseListIndex) in tabBarSearchList"
        :key="baseListIndex"
        class="tabBarSearchItem"
        @click="tabBarSearchItemClick(baseListItem)"
      >
        <view class="title">
          <text>{{ baseListItem.title }}</text>
        </view>
        <view>
          <u-icon
            :name="baseListItem.name"
            :size="12"
            color="rgb(83 83 83 / 50%)"
          ></u-icon>
        </view>
      </u-grid-item>
    </u-grid>

    <u-loading-page :loading="pageLoading"></u-loading-page>
    <scroll-view
      scroll-y
      refresher-enabled
      show-scrollbar
      :refresher-triggered="triggered"
      @refresherrefresh="$u.throttle(onRefresherrefresh, 200)"
      @scrolltolower="$u.throttle(onScrolltolower, 1000)"
      :style="{ height: `${screenHeight}px`, backgroundColor: '#fff' }"
    >
      <view
        v-if="listData.length === 0"
        :style="{ paddingTop: `${screenHeight / 4}px` }"
      >
        <u-empty mode="list" />
        <u-button
          class="empty-button"
          type="primary"
          text="新增"
          @tap="clickBtn({ key: 'btn1' })"
        ></u-button>
      </view>

      <view class="list-item" v-for="item in listData" :key="item.id">
        <view class="list-item-view" @click="goDetailPage(item)">
          <view class="list-item-avatar">
            <u-avatar shape="square" size="65"></u-avatar>
            <view class="selected line-1" v-if="selected(item) != 0"
              >已选{{selected(item)}}匹</view
            >
            <view class="m-t-36" v-else></view>
          </view>
          <view class="list-item-text">
            <view class="w-100p">
              <text class="label">{{ item.code }} {{ item.name }}</text>
            </view>
            <view
              v-if="
                page_source === 'dbd' ||
                page_source === 'cgd' ||
                page_source == 'xsd' ||
                page_source === 'khdd' ||
                page_source === 'cgdreturn'
              "
              class="bottom w-100p"
            >
              <text class="label">可发货</text>
              <text class="number">5匹</text>
              <text class="meter">309米</text>
            </view>
          </view>
        </view>
        <view v-if="showCon()">
          <u-button
            type="primary"
            shape="circle"
            size="small"
            throttleTime="1000"
            text="调库存"
            @click="inventoryAdjustmentPage(item)"
          ></u-button>
        </view>
      </view>
      <u-loadmore
        dashed
        line
        :status="status"
        loadingText="努力加载中"
        loadmoreText="轻轻上拉"
        nomoreText="实在没有了"
      />
    </scroll-view>

    <view :class="['bottom-submit', type]">
      <view
        class="info"
        v-if="
          page_source === 'cgd' ||
          page_source === 'xsd' ||
          page_source === 'thjs' ||
          page_source === 'khdd' ||
          page_source === 'cgdreturn' ||
          page_source === 'dbd'
        "
      >
        <view class="text">
          <text class="label">已选</text>
          <text class="value">{{ footList.num }}匹</text>
        </view>
        <view class="text">
          <text class="label">数量</text>
          <text class="value g">{{ footList.numHorses }} </text>
        </view>
      </view>
      <view class="button">
        <u-button
          v-if="
            page_source === 'dbd' ||
            page_source === 'cgd' ||
            page_source === 'xsd' ||
            page_source === 'thjs' ||
            page_source === 'khdd' ||
            page_source === 'cgdreturn'
          "
          type="primary"
          text="去结算"
          shape="circle"
          @click="toSettlement"
        ></u-button>
        <u-button
          v-if="page_source === 'sales'"
          type="primary"
          text="完成"
          shape="circle"
        ></u-button>
      </view>
    </view>

    <!-- 筛选弹框 - 1 -->
    <u-popup
      :show="statusShow"
      mode="bottom"
      overlayOpacity="0.3"
      @close="statusShowClose"
    >
      <view class="popup-bottom-view">
        <u-cell
          v-for="(item, index) in statusList"
          :key="index"
          :title="item.name"
          @click="targetStatus(item, index)"
        >
          <u-icon
            v-if="statusActive === index"
            slot="right-icon"
            size="20"
            color="#409EFF"
            name="checkmark"
          ></u-icon>
        </u-cell>
      </view>
    </u-popup>

    <!-- 筛选弹框 - 2 -->
    <u-popup
      :show="labelShow"
      mode="bottom"
      overlayOpacity="0.3"
      @close="labelShowClose"
    >
      <view class="popup-bottom-view">
        <u-cell
          v-for="(item, index) in labelList"
          :key="index"
          :title="item.name"
          @click="targetLabel(item, index)"
        >
          <u-icon
            v-if="labelActive === index"
            slot="right-icon"
            size="20"
            color="#409EFF"
            name="checkmark"
          ></u-icon>
        </u-cell>
      </view>
    </u-popup>

    <!-- 筛选弹框 - 4 -->
    <u-popup
      class="sidebar"
      :show="show"
      mode="right"
      overlayOpacity="0.3"
      @close="show = false"
    >
      <view class="pop-view">
        <view>
          <cx-select-customer
            :label="searchData.catName"
            title="类别"
            @inputproductInformationdetailComponentsCategory="categoryInput"
            @update:labelproductInformationdetailComponentsCategory="
              categoryLabel
            "
            name="productInformationdetailComponentsCategory"
          />
          <cx-select-customer title="季度" name="SelectQuarter" />
          <cx-select-customer title="工艺" name="SelectTechnology" />
          <u-cell title="显示可发数">
            <view slot="value">
              <u-switch v-model="showNumberSend"></u-switch>
            </view>
          </u-cell>
          <u-cell title="隐藏0可发">
            <view slot="value">
              <u-switch v-model="showHideSend"></u-switch>
            </view>
          </u-cell>
          <u-cell title="显示只拿过的产品">
            <view slot="value">
              <u-switch v-model="showOnlyTakenProducts"></u-switch>
            </view>
          </u-cell>
        </view>
        <view class="fot-btn flex flex-sw p-l-10 p-r-10">
          <u-button
            text="重置"
            @click="
              () => {
                searchData = {
                  catIds: [],
                  catName: null,
                };
              }
            "
            shape="circle"
            class="reset m-r-10"
          ></u-button>
          <u-button
            text="搜索"
            @click="
              () => {
                listData = [];
                pageInfo.current = 1;
                listPage();
                show = false;
              }
            "
            shape="circle"
            color="linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246))"
          ></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  listOptionsPage,
  getGoodsInfoForBillDetailBySpuIds,
} from "@/apis/bill/goodSpu";
import { getlist } from "@/apis/bill/information/warehouse";

export default {
  name: "customer-product",
  computed: {},
  onLoad({ id, type = "", name, source }) {
    this.type = type;
    this.name = name;
    this.page_source = source;
    this.initData();
  },
  onShow() {
    // 获取仓库的信息
    uni.$on("on-warehouse-data", (data) => {
      this.warehouse = data;
      uni.$off("on-warehouse-data");
    });

    // 获取调库存的信息
    uni.$on("inventoryAdjustment", (data, arr) => {
      // 循环data 都放到dataItem.productInformation里面
      if (this.page_source == "xsd") {
        let dataItem = this.$ls.get("xsdInformation");
        data.forEach((e) => {
          dataItem.productInformation.push(e);
        });
        this.$ls.set("xsdInformation", dataItem);
      } else if (this.page_source == "cgdreturn") {
        let dataItem = this.$ls.get("cgdreturnInformation");
        data.forEach((e) => {
          dataItem.productInformation.push(e);
        });
        this.$ls.set("cgdreturnInformation", dataItem);
      }else if (this.page_source == "dbd") {
        let dataItem = this.$ls.get("dbdInformation");
        data.forEach((e) => {
          dataItem.productInformation.push(e);
        });
        this.$ls.set("dbdInformation", dataItem);
      }

      this.countNumAnHorses();
    });
    // 更新下面已选和数量的值
    this.countNumAnHorses();
  },
  mounted() {
    const height =
      this.$refs.hxnb.$el.offsetHeight +
      this.$refs.tabBarSearch.$el.offsetHeight * 3 +
      (this.page_source === "sales" ? 0 : 62);
    const sysInfo = uni.getSystemInfoSync();
    this.screenHeight =
      sysInfo.windowHeight - (this.page_source === "sales" ? 0 : height) - 7;
  },
  data() {
    return {
      status: "loadmore", // 加载更多状态
      footList: {
        num: 0,
        numHorses: 0,
      },
      // 加工商名字
      name: "",
      // 页面来源
      page_source: "",
      config: {
        title: "产品",
        color: "#ffffff",
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          {
            key: "btn1",
            icon: "&#xe727;",
            position: "left",
          },
          {
            key: "btn2",
            icon: "&#xe888;",
            position: "left",
          },
        ],
      },
      // 显示调库存按钮白名单
      whiteList: ["return", "xsd", "procure", "cgdreturn", "dbd"],

      type: "",

      tabBarSearchList: [
        {
          name: "arrow-down-fill",
          title: "全部",
          key: "status",
          show: false,
        },
        {
          name: "arrow-down-fill",
          title: "标签",
          key: "label",
          show: false,
        },
      ],

      labelShow: false,
      labelList: [
        { name: "面料好" },
        { name: "时尚" },
        { name: "百搭" },
        { name: "悠闲" },
        { name: "推荐" },
        { name: "花型好看" },
      ],
      labelActive: 0,

      statusShow: false,
      statusList: [
        { name: "全部" },
        { name: "成品" },
        { name: "坯布" },
        { name: "已上架" },
        { name: "已下架" },
      ],
      statusActive: 0,

      show: false,
      showNumberSend: true,
      showHideSend: false,
      showOnlyTakenProducts: false,
      warehouse: {},

      listData: [],
      pageInfo: {
        current: 1, // 当前页
        size: 15, // 每页数据条数
        order: "desc", // 排序方向
      },
      searchData: {
        catName: "",
        catIds: [],
      },
      pageLoading: false,
      triggered: false,
      screenHeight: 0,
      storageData: null, // 存储下当前数据 方便选库存的时候存上
    };
  },
  methods: {
    categoryInput(e) {
      this.searchData.catIds[0] = e;
    },
    categoryLabel(e) {
      this.searchData.catName = e;
    },
    countNumAnHorses() {
      let num = 0;
      let numHorses = 0;
      let dataItem = {};
      if (this.page_source == "xsd") {
        dataItem = this.$ls.get("xsdInformation");
      } else if (this.page_source == "cgd") {
        dataItem = this.$ls.get("cgdInformation");
      } else if (this.page_source == "thjs") {
        dataItem = this.$ls.get("thjsInformation");
      } else if (this.page_source == "khdd") {
        dataItem = this.$ls.get("khddInformation");
      } else if (this.page_source == "cgdreturn") {
        dataItem = this.$ls.get("cgdreturnInformation");
      } else if (this.page_source == "dbd") {
        dataItem = this.$ls.get("dbdInformation");
      }
      for (let i = 0; i < dataItem?.productInformation?.length; i++) {
        num += Number(dataItem.productInformation[i].piecesCount)
        numHorses += Number(
            dataItem.productInformation[i].quantity
          );
      }
      this.footList.numHorses = numHorses;
      this.footList.num = num;
    },
    showCon() {
      return this.whiteList.includes(this.page_source);
    },
    // 去结算
    toSettlement() {
      // 采购 == 采购单结算
      switch (this.page_source) {
        case "xsd":
          uni.redirectTo({
            url: `/pages/application/pages/cloth/procure/settlement/sales`,
          });
          // uni.redirectTo({
          //   url: `/pages/application/pages/cloth/procure/settlement/procure-order-settlement`
          // })
          break;
        case "thjs":
          uni.redirectTo({
            url: `/pages/application/pages/cloth/procure/settlement/sales`,
          });
          // uni.redirectTo({
          //   url: `/pages/application/pages/cloth/procure/settlement/procure-order-settlement`
          // })
          break;
        // 采购订单结算页进入
        case "cgd":
          uni.redirectTo({
            url: `/pages/application/pages/cloth/procure/settlement/index`,
          });
          break;
        case "khdd":
          uni.redirectTo({
            url: `/pages/application/pages/cloth/procure/settlement/customer-orders`,
          });
          break;
        case "cgdreturn":
          uni.redirectTo({
            url: `/pages/application/pages/cloth/procure/settlement/cgd-return`,
          });
          break;
        case "dbd":
          uni.redirectTo({
            url: `/pages/application/pages/cloth/procure/settlement/transfer-order`,
          });
          break;
      }
    },
    selected(item) {
      let data = {};
      if (this.page_source == "xsd") {
        data = this.$ls.get("xsdInformation");
      } else if (this.page_source == "cgd") {
        data = this.$ls.get("cgdInformation");
      } else if (this.page_source == "thjs") {
        data = this.$ls.get("thjsInformation");
      } else if (this.page_source == "khdd") {
        data = this.$ls.get("khddInformation");
      } else if (this.page_source == "cgdreturn") {
        data = this.$ls.get("cgdreturnInformation");
      } else if (this.page_source == "dbd") {
        data = this.$ls.get("dbdInformation");
      }
      if (!data || data.productInformation.length == 0) {
        return 0;
      }
      return data.productInformation
        .filter((obj) => obj.spuId === item.spuId)
        .reduce((acc, obj) => {
          const count = Number(obj.piecesCount);
          return isNaN(count) ? acc : acc + count;
        }, 0);
    },
    clickBtn(item) {
      console.log("xsdInformation", this.$ls.get("xsdInformation"));
      return;
      if (item.key === "btn1") {
        uni.navigateTo({
          url: "pages/application/pages/information/product-information/detail/index",
        });
      }
      if (item.key === "btn2") {
        this.show = true;
      }
    },
    onSearchChange() {
      this.handlerSearch();
    },
    tabBarSearchItemClick({ key }) {
      const index = this.tabBarSearchList.findIndex((item) => item.key === key);
      const checkShow = !this.tabBarSearchList[index].show;
      this.tabBarSearchList[index].show = checkShow;
      this.tabBarSearchList[index].name = checkShow
        ? "arrow-up-fill"
        : "arrow-down-fill";

      if (key === "status") return (this.statusShow = true);
      if (key === "label") return (this.labelShow = true);
    },
    statusShowClose() {
      this.statusShow = false;
      this.tabBarSearchList[0].show = false;
      this.tabBarSearchList[0].name = "arrow-down-fill";
    },
    targetStatus(item, index) {
      this.statusActive = index;
      this.statusShow = false;
      this.tabBarSearchList[0].show = false;
      this.tabBarSearchList[0].name = "arrow-down-fill";
    },
    labelShowClose(item, index) {
      this.labelShow = index;
      this.statusShow = false;
      this.tabBarSearchList[1].show = false;
      this.tabBarSearchList[1].name = "arrow-down-fill";
    },
    targetLabel(item, index) {
      this.labelActive = index;
      this.labelShow = false;
      this.tabBarSearchList[1].show = false;
      this.tabBarSearchList[1].name = "arrow-down-fill";
    },
    changeWarehouse() {
      uni.navigateTo({
        url: `/pages/application/pages/information/warehouse/warehouse?type=list`,
      });
    },
    onRefresherrefresh() {
      this.triggered = true;
      this.pageInfo.current = 1;
      this.listData = [];
      this.listPage();
    },
    handlerSearch: _.debounce(function () {
      this.listData = [];
      this.pageInfo.current = 1;
      this.listPage();
    }, 200),
    initData() {
      let billId = {
        data: {
          isEnable: true,
        },
        page: {
          current: 1,
          size: 10,
          sort: "",
          order: "desc",
          total: 0,
          orders: [
            {
              column: "create_time",
              asc: false,
            },
          ],
        },
      };
      getlist(billId).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        // 默认拿第一个仓库的数据
        this.warehouse = data.records[0];
      });

      this.listPage();
    },
    listPage() {
      const params = {
        page: this.pageInfo,
        data: this.searchData,
      };
      uni.showLoading({
        title: "加载中",
      });
      this.status = "loading";
      listOptionsPage(params)
        .then((res) => {
          if (!res.data.flag) return;
          const records = res.data.data.records || [];
          if (records.length <= 10) {
            this.status = "nomore";
          } else {
            this.status = "loadmore";
          }
          this.listData.push(...records);
        })
        .finally((_) => {
          this.triggered = false;
          this.pageLoading = false;
          uni.hideLoading();
        });
    },
    onScrolltolower() {
      this.pageInfo.current += 1;
      this.listPage();
    },
    goDetailPage(item) {
      console.log("item",item);
      console.log("page_source",this.page_source);
      console.log("warehouse",this.warehouse);
      let likeList = this.$getPageParams("djRowItem")?.likeList || [
        { label: "宽幅/克重", check: true },
        { label: "规格", check: true },
        { label: "缸号", check: true },
        { label: "批号", check: true },
        { label: "辅编号/名称", check: true },
      ];

      // type == 'cgd' 等于进入采购单逻辑
      // 采购单的所有信息都存储在 cgdInformation 中
      // 存储当前条产品信息
      getGoodsInfoForBillDetailBySpuIds([
        {
          spuId: item.spuId,
          comegoId: null,
        },
      ]).then((res) => {
        if (!res.data.flag) return;
        const data = res.data.data || {};
        let config = Object.assign(data[0], item);
        if (
          this.page_source === "xsd" ||
          this.page_source === "cgd" ||
          this.page_source === "cgdreturn"
        ) {
          // if (!this.warehouse.isBatchNumber) {
          //   this.inventoryAdjustmentPage(item);
          // } else {
            // 存储当前数据到下个页面
            this.$setPageParams("djRowItem", {
              list: Object.assign(config, {
                storeName: this.warehouse.name || "",
                storeId: this.warehouse.id || "",
              }),
              info: {
                isEcho: false,
                index: 0,
              },
              likeList: likeList,
            });
            // 传递当前数据
            this.$Router.push({
              path: `/pages/application/pages/cloth/color/index?source=${this.page_source}`,
            });
          // }
        } else if (this.page_source === "thjs") {
          this.$setPageParams("djRowItem", {
            list: Object.assign(config, {
              storeName: this.warehouse.name || "",
              storeId: this.warehouse.id || "",
            }),
            info: {
              isEcho: false,
              index: 0,
            },
            likeList: likeList,
          });
          // 传递当前数据
          this.$Router.push({
            path: `/pages/application/pages/cloth/color/index?source=${this.page_source}`,
          });
        } else if (this.page_source === "khdd") {
          this.$setPageParams("djRowItem", {
            list: Object.assign(config, {
              storeName: this.warehouse.name || "",
              storeId: this.warehouse.id || "",
            }),
            info: {
              isEcho: false,
              index: 0,
            },
            // 存储当前的偏好设置
            likeList: likeList,
          });
          // 传递当前数据
          this.$Router.push({
            path: `/pages/application/pages/cloth/color/index?source=${this.page_source}`,
          });
        }else if(this.page_source === "dbd"){
            this.$setPageParams("djRowItem", {
              list: Object.assign(config, {
                storeName: this.warehouse.name || "",
                storeId: this.warehouse.id || "",
              }),
              info: {
                isEcho: false,
                index: 0,
              },
              likeList: likeList,
            });
            this.inventoryAdjustmentPage(item);
        }
      });
    },
    inventoryAdjustmentPage(item) {
      this.storageData = item;
      uni.navigateTo({
        // url: `/pages/application/pages/cloth/customer-inventory-adjustment/index?code=${item.code}&name=${item.name}&spuId=${item.spuId}&id=${this.warehouse.id}&name=${this.warehouse.name}`
        url: `/pages/application/pages/cloth/inventory-adjustment/index?code=${item.code}&name=${item.name}&spuId=${item.spuId}&storeId=${this.warehouse.id}&storeName=${this.warehouse.name}`,
      });
    },
  },
  beforeDestroy() {
    uni.$off("on-warehouse-data");
    uni.$off("inventoryAdjustment");
  },
};
</script>


<style scoped lang="scss">
.pop-view {
  width: 500rpx;
  padding-top: 270rpx;

  .fot-btn {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding-bottom: 20rpx;
  }

  .reset {
    color: #409eff;
    background-color: #e3edff;
  }
}

.popup-bottom-view {
  padding: 20upx 10upx;
}

.tabBarSearch {
  justify-content: space-evenly !important;
  margin-top: 185upx;
  padding-top: 20upx;
  padding-bottom: 20upx;
  border-bottom: 1upx #dadada solid;
  background-color: #fff;

  &.sales {
    margin-top: 110rpx;
  }

  .tabBarSearchItem {
    display: flex;
    flex-direction: row;
    align-items: center;

    .title {
      margin-right: 20upx;
      color: #535353bf;
    }
  }
}

.input-product {
  width: 95%;
  margin: 20upx auto;
  border-radius: 50upx;
  height: 70upx;
  line-height: 70upx;
  color: #fff;
}

.search-title {
  display: flex;
  justify-content: center;
  align-content: center;
  align-items: center;
  padding-top: 5rpx;
  padding-bottom: 20rpx;

  .label {
    font-size: 32rpx;
  }

  .warehouse {
    border: 2rpx solid #fff;
    margin-left: 15rpx;
    padding: 5rpx;
  }
}

.list-item {
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
  padding: 0px 15px;
  font-size: 15px;
  color: #303133;
  align-items: center;
}

.list-item-view {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  .selected {
    position: relative;
    bottom: 36rpx;
    left: 0;
    background: #f96161;
    color: #fff;
    width: 128rpx;
    font-size: 12px;
    display: flex;
    justify-content: center;
  }
}

.list-item-text {
  flex: 1;
  padding-left: 30rpx;
  height: 130rpx;
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  .title {
    font-size: 30rpx;
  }

  .bottom {
    margin-top: 20rpx;
    font-size: 26rpx;

    .label {
      color: #ababab;
    }

    .number {
      margin-left: 15rpx;
      color: #29b929;
    }

    .meter {
      margin-left: 15rpx;
      color: #87e0ff;
    }
  }
}

.bottom-submit {
  position: fixed;
  bottom: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 750rpx;
  height: 100rpx;
  background-color: #ffffff;
  z-index: 1;
  padding: 10rpx 30rpx;
  padding-top: 15rpx;

  &.sales {
    justify-content: flex-end;
  }

  .info {
    .text {
      .label {
        font-size: 30rpx;
        color: #ababab;
      }

      .value {
        margin-left: 15rpx;
        font-size: 30rpx;
        color: #29b929;

        &.g {
          color: #87e0ff;
        }
      }
    }
  }

  .button {
    width: 50%;
  }
}

.empty-button {
  margin: auto;
  margin-top: 20rpx;
  width: 80%;
}
</style>

